package com.bwie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Users;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.remote.UserRemote;
import com.bwie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserRemote userRemote;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public UserResponse login(String tel) {

        if(StrUtil.isBlank(tel)){
            throw new RuntimeException("手机号不能为空");
        }
        if (!tel.matches("1[3-9][0-9]{9,}")) {
            throw new RuntimeException("手机号格式不正确");
        }

        //远程掉用
        Result<Users> result = userRemote.login(tel);

        if(result.equals(Result.SUCCESS)){
            throw new RuntimeException("用户存在");
        }

        Users data = result.getData();

        if(data==null){
            throw new RuntimeException("用户不存在");
        }
        Map<String, Object> map = new HashMap<>();
        String userKey = UuidUtils.generateUuid();
        map.put(JwtConstants.USER_KEY, userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSON.toJSONString(data),30, TimeUnit.MINUTES);
        UserResponse response = new UserResponse();
        response.setToken(token);
        response.setUserTime("30MIN");
        return response;
    }
}
